package com.flainsky.nirvanaplayer.adpters;

import java.util.List;

import org.videolan.vlc.android.VideoPlayerActivity;

import com.flainsky.nirvanaplayer.R;
import com.flainsky.nirvanaplayer.cache.ImageCache;
import com.flainsky.nirvanaplayer.globe.DownloadUtils;
import com.flainsky.nirvanaplayer.globe.GlobeCache;
import com.flainsky.nirvanaplayer.globe.PlayController;
import com.flainsky.nirvanaplayer.globe.DownloadUtils.DataType;
import com.flainsky.nirvanaplayer.lib.objects.Movie;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;

public class ShowListAdapter extends BaseAdapter {

	private Context mContext;
	private List<Movie> mList;
	private ImageCache cache;
	ProgressDialog pdialog;
	
	public void setList(List<Movie> list)
	{
		mList = list;
	}
	
	public ShowListAdapter(Context context,List<Movie> list)
	{
		mContext = context;
		mList = list;
		cache = GlobeCache.getInstance().getCache();
		
		pdialog = new ProgressDialog(mContext);
    	pdialog.setButton("cancel", new DialogInterface.OnClickListener() {
	         public void onClick(DialogInterface dialog, int i) {
	        	 dialog.cancel();
	         }
	    });
    	pdialog.setTitle(R.string.wait);
        pdialog.setCancelable(true);
        pdialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
	}
	
	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		if(mList == null)
			return 0;
		Log.d("cache", "adpater count "+String.valueOf(mList.size()));
		return mList.size();
	}

	@Override
	public Object getItem(int position) {
		// TODO Auto-generated method stub
		if(mList == null)
			return null;
		return mList.get(position);
	}

	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		if(mList == null)
			return 0;
		return mList.get(position).mId;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		// TODO Auto-generated method stub
		final Movie movie = mList.get(position);
		if(convertView == null)
		{
			LayoutInflater inflater=LayoutInflater.from(mContext);
			convertView = inflater.inflate(R.layout.moive_info_land_item, null);
		}
		ImageView sIv = (ImageView)convertView.findViewById(R.id.simage);
		sIv.setImageResource(R.drawable.loading2);
		TextView title = (TextView)convertView.findViewById(R.id.tv_title);
		TextView year = (TextView)convertView.findViewById(R.id.tv_year_tag);
		TextView episod = (TextView)convertView.findViewById(R.id.tv_episod);
		TextView director = (TextView)convertView.findViewById(R.id.director_tv);
		TextView leader = (TextView)convertView.findViewById(R.id.leader_tv);
		TextView info = (TextView)convertView.findViewById(R.id.info_tv);
		RatingBar rb = (RatingBar)convertView.findViewById(R.id.rb);
		ImageView play = (ImageView)convertView.findViewById(R.id.play_iv);
		
		sIv.setTag(movie.mSimage);
		title.setText(movie.mTitle);
		year.setText(mContext.getString(R.string.year)+movie.mYear);
		episod.setText(mContext.getString(R.string.episod)+movie.mNum_episode);
		director.setText(mContext.getString(R.string.director)+movie.mDirector);
		String roles = mContext.getString(R.string.lead_role);
		for(String str : movie.mLeading_role)
		{
			roles +=(" "+str);
		}
		leader.setText(roles);
		info.setText(movie.mIntro);
		rb.setRating(movie.mComment);
		play.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				//PlayController.getInstance().setCurrentPlayUrl(movie.mPlay_url);
				PlayController.getInstance().setCurrentPlayMovie(movie);
				LoadingVideoAsyncTask loadingVideo = new LoadingVideoAsyncTask();
				loadingVideo.execute();
			}
		});
		if(cache.containsKey(movie.mId))
		{
			sIv.setImageBitmap(cache.get(GlobeCache.MULTIPLE_OF_SMALL*movie.mId));
		}
		else
		{
			DownloadImageAsyncTask task = new DownloadImageAsyncTask(movie.mSimage, sIv, movie.mId);
			task.execute();
		}
		Log.d("cache", "get contentview");		
		return convertView;
	}
	public class DownloadImageAsyncTask extends AsyncTask<Void, Void, Void> {

		String mUrl;
		ImageView mIv;
		int mId;
		boolean isFinish = false;
		boolean isNotExit = false;
		public DownloadImageAsyncTask(String url,ImageView iv,int id)
		{
			mUrl = url;
			mIv = iv;
			mId = id;
		}
		@Override
		protected void onPreExecute()
		{
			if(!mUrl.equals(mIv.getTag()))
			{
				isFinish = true;
			}
		}
		
		@Override
		protected Void doInBackground(Void... params) {
			// TODO Auto-generated method stub
			if(!isFinish)
			{
				isNotExit = !DownloadUtils.downloadFile(mContext,mUrl,DownloadUtils.DataType.image);
			}
			return null;
		}
		
		@Override
	    protected void onPostExecute(Void result) {
			if(isNotExit)
			{
				Toast.makeText(mContext, mUrl+" file not exits in server!",Toast.LENGTH_LONG).show();
				return;
			}
			if(!mUrl.equals(mIv.getTag()))
			{
				Log.d("cache", mUrl+" out of date");
				return;
			}
			if(mIv!=null)
			{
				if(isFinish)return;
				String str = DownloadUtils.getUrlName(mUrl);
				String path = DownloadUtils.getDataParentPath(DataType.image)+str;
				Bitmap bmp = BitmapFactory.decodeFile(path);
				cache.put(mId*GlobeCache.MULTIPLE_OF_SMALL, bmp);
				mIv.setImageBitmap(bmp);
			}
		}
	}
	
	private void play()
	{
		Intent intent = new Intent(mContext,VideoPlayerActivity.class);
		mContext.startActivity(intent);
	}
	
	private class LoadingVideoAsyncTask extends AsyncTask<Void, Void, Void> {
		boolean isNotExit = false;
		public LoadingVideoAsyncTask()
		{
			pdialog.setMessage(mContext.getString(R.string.video_loading));
		}
		
		@Override
		protected void onPreExecute()
		{
			if(pdialog!=null && !pdialog.isShowing())
			{
				pdialog.show();
			}
		}
		
		@Override
		protected Void doInBackground(Void... params) {
			// TODO Auto-generated method stub
			isNotExit = !DownloadUtils.downloadFile(mContext,PlayController.getInstance().getCurrentPlayUrl(), DataType.movie);
			return null;
		}
		
		@Override
	    protected void onPostExecute(Void result) {
			if(pdialog != null && pdialog.isShowing())
			{
				pdialog.dismiss();
			}
			if(isNotExit)
			{
				Toast.makeText(mContext, PlayController.getInstance().getCurrentPlayUrl()+" file not exits in server!",Toast.LENGTH_LONG).show();
				return;
			}
			play();
		}
	}
}
